package com.lovezy.platform.core.valid.validators;


import com.lovezy.platform.core.exception.ValidationException;
import com.lovezy.platform.core.valid.Validator;
import com.lovezy.platform.core.valid.annotation.NotEmptyArray;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;

/**
 * 数组信息校验器
 * Created by jin on 2016/12/30.
 */
public class ArrayValidator implements Validator {
    @Override
    public void validate(Object value, Annotation annotation) throws ValidationException {
        NotEmptyArray array = (NotEmptyArray) annotation;
        if (value != null) {
            if (value.getClass().isArray()) {
                if (Array.getLength(value) > 0) {
                    return;
                }
            } else if (value instanceof Iterable) {
                Iterable iterable = (Iterable) value;
                if(iterable.iterator().hasNext()){
                    return;
                }
            }
        }
        throw new ValidationException(array.errorCode(), array.errorMsg());
    }

}
